package com.surelution.projects.crm
import java.util.Map;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.grails.plugins.excelimport.ExcelImportUtils;
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import groovy.time.TimeCategory

class CompetitorStationController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def pictureService
	def springSecurityService
	
	static Map CONFIG_STATION_MAP = [
		sheet:"station",
		startRow: 1,
		columnMap:  [
			'B':'name',
			'C':'address',
			'D':'managerTel',
		]
	]
	
    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 15, 100)
		OwnStation station1 = User.findByUsername(springSecurityService.principal.username).station
		def station2 = params['station.id']?OwnStation.get(params['station.id']):null
        def s = springSecurityService.principal.username=='admin'?'':station1
	    def station =  station2?station2:s
	    def result = CompetitorStation.createCriteria().list([max:params.max, offset:params.offset]){
		  if(station){
			  eq("station",station)
		  }
	    }
        [competitorStationInstanceList:result, competitorStationInstanceTotal: result.totalCount]
    }
	
	def editList = {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[competitorStationInstanceList: CompetitorStation.list(params), competitorStationInstanceTotal: CompetitorStation.count()]
	}
	
	def ImportExcelService

	def stationImport = {
		
	}

	def sImport = {
		def file = params.stationFile
		def fileName = file.originalFilename
		Workbook workbook = WorkbookFactory.create(file.inputStream)
		List competitorList = ExcelImportUtils.columns(workbook, CONFIG_STATION_MAP)
		println competitorList
		competitorList.each{
			println it
			if (!CompetitorStation.findByName(it.get("name"))){
				CompetitorStation competitorStationInstance = new CompetitorStation(name:"${it.get("name")}",address:"${it.get("address")}",
					managerTel:"${it.get("managerTel")}")
				competitorStationInstance.hasShop=false
				competitorStationInstance.level = Level.get(1)
				competitorStationInstance.star = StarLevel.get(1)
				competitorStationInstance.tonLevel = TonLevel.get(1)
				competitorStationInstance.company = CompetitorCompany.get(1)
				OwnStation station = User.findByUsername(springSecurityService.principal.username).station
				competitorStationInstance.station = station
				competitorStationInstance.stationArea = station.stationArea
				competitorStationInstance.isLocked = false
				competitorStationInstance.latitude = 0
				competitorStationInstance.longitude = 0
				competitorStationInstance.save()
				println competitorStationInstance
			}
			else{
				println "repeat ${CompetitorStation.findByName(it.get("name")).name}"
			}
		}
		ImportExcel excel = ImportExcelService.storeFile(file.inputStream,fileName)
		excel.uploader = springSecurityService.principal.username
		excel.type = "竞争对手网点分布"
		excel.save()
		flash.message = "${message(code: 'default.updateFileSuccess.message', args: [message(code: 'competitorStation.label', default: 'competitorStation')])}"
		redirect(action: "list")
	}
	
	def reset = {
		def competitorStationInstance = new CompetitorStation()
		competitorStationInstance.latitude = params.lat
		competitorStationInstance.longitude = params.lng
		OwnStation station1 = User.findByUsername(springSecurityService.principal.username).station
		
		def station = springSecurityService.principal.username=='admin'?'':station1
		def result = CompetitorStation.createCriteria().list([max:params.max, offset:params.offset]){
			if(station){
				eq("station",station)
			}
			eq("isLocked", false)
		}
		if (!competitorStationInstance) {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'competitorStation.label', default: 'competitorStation'), params.id])}"
			redirect(action: "list")
		}
		else {
			return [competitorStationInstance: competitorStationInstance,competitorStationList:result]
		}
	}
	
	def resetPosition = {
		def competitorStationInstance = CompetitorStation.get(params.id)
		if (competitorStationInstance) {
			if (params.version) {
				def version = params.version.toLong()
				if (competitorStationInstance.version > version) {
					competitorStationInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'competitorStation.label', default: 'competitorStation')] as Object[], "Another user has updated this competitorStation while you were editing")
					render(view: "edit", model: [competitorStationInstance: competitorStationInstance])
					return
				}
			}
			competitorStationInstance.properties = params
			if (!competitorStationInstance.hasErrors() && competitorStationInstance.save(flush: true)) {
				flash.message = "${message(code: 'default.updated.message', args: [message(code: 'competitorStation.label', default: 'competitorStationInstance'), competitorStationInstance.id])}"
				redirect(action: "show", id: competitorStationInstance.id)
			}
			else {
				render(view: "edit", model: [competitorStationInstance: competitorStationInstance])
			}
		}
		else {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'competitorStation.label', default: 'competitorStationInstance'), params.id])}"
			redirect(action: "list")
		}
	}
	
	def unLock = {
		def competitorStationInstance = CompetitorStation.get(params.id)
		flash.message = "${message(code: 'default.updated.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), competitorStationInstance.id])}"
		if (competitorStationInstance) {
			competitorStationInstance.isLocked = false
			redirect(action: "editList")
		}
		else {
			redirect(action: "editList")
		}
	}
	
	def locked = {
		def competitorStationInstance = CompetitorStation.get(params.id)
		flash.message = "${message(code: 'default.updated.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), competitorStationInstance.id])}"
		if (competitorStationInstance) {
			competitorStationInstance.isLocked = true
			redirect(action: "editList")
		}
		else {
			redirect(action: "editList")
		}
	}
	
	def exportService
	
	def export = {
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
		response.setHeader("Content-disposition", "attachment; filename=competitor.xls")
		def result = CompetitorStation.list()
		def mapList = new ArrayList<HashMap>()
		result.each {
			def map = new HashMap()
			if (it.stationArea){
				map.put("stationArea", it.stationArea.areaName)
			}
			else map.put("stationArea", "")
			map.put("name", it.name)
			map.put("company", it.company.name)
			map.put("station", it.station.name)
			map.put("address", it.address)
			map.put("manager", it.manager)
			map.put("managerTel", it.managerTel)
			map.put("annualSale", it.annualSale)
			map.put("noGasAnnualSale", it.noGasAnnualSale)
			map.put("averageSale", it.averageSale)
			map.put("noGasAnnualSale", it.noGasAnnualSale)
			map.put("gasFuel", it.gasFuel)
			map.put("latitude", it.latitude)
			map.put("longitude", it.longitude)
			mapList.add(map)
		}
		List fields = ["stationArea","name","company","station","address","manager","managerTel","annualSale","noGasAnnualSale","averageSale","noGasAnnualSale","gasFuel","longitude","latitude"]
		Map labels = ["stationArea":"片区","name":"站名","company":"所属公司","station":"对应自有加油站","address":"地址","manager":"联系人","managerTel":"站内电话","annualSale":"油品年度总销量(吨)","noGasAnnualSale":"非油年度总销量","averageSale":"油品日均销量(吨)","noGasAverageSale":"非油日均销量","gasFuel":"柴汽比","latitude":"经度","longitude":"纬度"]

		exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		}

    def create = {
        def competitorStationInstance = new CompetitorStation()
		competitorStationInstance.latitude = params.lat
		competitorStationInstance.longitude = params.lng
        competitorStationInstance.properties = params
		
		def result = CompetitorCompany.createCriteria().list(){
			gt("id",(Long)1)
		}
		
		def result1 = CompetitorCompany.list()
		def comList = springSecurityService.principal.username=='admin'?result1:result
        return [competitorStationInstance: competitorStationInstance,comList:comList]
    }

    def save = {
        def competitorStationInstance = new CompetitorStation(params)
		competitorStationInstance.hasShop=false
		competitorStationInstance.level = Level.get(1)
		competitorStationInstance.star = StarLevel.get(1)
		competitorStationInstance.tonLevel = TonLevel.get(1)
		OwnStation station = User.findByUsername(springSecurityService.principal.username).station
		competitorStationInstance.station = station
		competitorStationInstance.stationArea = station.stationArea
		competitorStationInstance.isLocked = false
		competitorStationInstance.latitude = 0
		competitorStationInstance.longitude = 0
        if (competitorStationInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), competitorStationInstance.id])}"
            redirect(action: "show", id: competitorStationInstance.id)
        }
        else {
            render(view: "create", model: [competitorStationInstance: competitorStationInstance])
        }
    }

    def show = {
        def competitorStationInstance = CompetitorStation.get(params.id)
        if (!competitorStationInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), params.id])}"
            redirect(action: "list")
        }
        else {
			Date now = new Date()
			def year = now.year+1900
            [competitorStationInstance: competitorStationInstance,year:year]
        }
    }

    def edit = {
        def competitorStationInstance = CompetitorStation.get(params.id)
        if (!competitorStationInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [competitorStationInstance: competitorStationInstance]
        }
    }
	
	def editSale = {
		def competitorStationInstance = CompetitorStation.get(params.id)
		println competitorStationInstance
		if (!competitorStationInstance) {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), params.id])}"
			redirect(action: "list")
		}
		else {
			return [competitorStationInstance: competitorStationInstance]
		}
	}

	def updatePic = {
		def competitorStationInstance = CompetitorStation.get(params.id)
		if (competitorStationInstance) {
			if (params.version) {
				def version = params.version.toLong()
				if (competitorStationInstance.version > version) {
					competitorStationInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'ownStation.label', default: 'OwnStation')] as Object[], "Another user has updated this OwnStation while you were editing")
					render(view: "edit", model: [competitorStationInstance: competitorStationInstance])
					return
				}
			}
			else{
				flash.message = "${message(code: 'default.null.picture')}"
				redirect(action: "show", id: competitorStationInstance.id)
			}
			competitorStationInstance.properties = params
			if (!competitorStationInstance.hasErrors()) {
				def file = params.ComPicture
				def title = params.pictureTitle
				def description = params.description
				if(title == "" && !file.isEmpty()) {
					flash.message = "${message(code: 'default.not.found.title')}"
					redirect(action: "show", id: competitorStationInstance.id)
				}
				if(title != "" && !file.isEmpty()) {
					Picture picture = pictureService.storePicture(file.inputStream)
					picture.title = title
					picture.description = description
					picture.save(flush:true)
					
					StationPicture stationPicture = new StationPicture()
					stationPicture.station = competitorStationInstance
					stationPicture.picture = picture
					stationPicture.isDefault = false
					try{
						competitorStationInstance.addToPictures(stationPicture)
						stationPicture.save(flush:true)
					}catch(e) {
						e.printStackTrace()
					}
					flash.message = "${message(code: 'default.updated.message', args: [message(code: 'competitorStation.label', default: 'competitorStation'), competitorStationInstance.id])}"
					redirect(action: "show", id: competitorStationInstance.id)
				}
			}
			else {
				flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'competitorStation.label', default: 'competitorStation'), params.id])}"
				redirect(action: "list")
			}
		}
	}
	
    def update = {
        def competitorStationInstance = CompetitorStation.get(params.id)
        if (competitorStationInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (competitorStationInstance.version > version) {
                    
                    competitorStationInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'competitorStation.label', default: 'CompetitorStation')] as Object[], "Another user has updated this CompetitorStation while you were editing")
                    render(view: "edit", model: [competitorStationInstance: competitorStationInstance])
                    return
                }
				
            }
			competitorStationInstance.properties = params
			if (params.station.id){
				competitorStationInstance.stationArea = OwnStation.get(params.station.id).stationArea
			}
            if (!competitorStationInstance.hasErrors() && competitorStationInstance.save(flush: true)) {
					flash.message = "${message(code: 'default.updated.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), competitorStationInstance.id])}"
	                redirect(action: "show", id: competitorStationInstance.id)
            }
	        else {
	            flash.message = "${message(code: 'default.error.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), params.id])}"
	            redirect(action: "show", id: competitorStationInstance.id)
	        }
        }
    }

    def delete = {
        def competitorStationInstance = CompetitorStation.get(params.id)
        if (competitorStationInstance) {
            try {
                competitorStationInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'competitorStation.label', default: 'CompetitorStation'), params.id])}"
            redirect(action: "list")
        }
    }
	
	def gasPriceService
	def comparePrice = {
		def mapList
		def startDay = new Date()
		def endDay 
		use(TimeCategory) {
			endDay = startDay + 1.day
		}
		use(TimeCategory) {
			endDay = startDay + 1.day
		}
		mapList = comparePriceReport(startDay,endDay)
		[result:mapList,startDay:startDay,endDay:endDay]
    }
	def comparePriceExport = {
		def mapList
		def startDay = new Date()
		def endDay
		use(TimeCategory) {
			endDay = startDay + 1.day
		}
		mapList = comparePriceReport(startDay,endDay)
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
		response.setHeader("Content-disposition", "attachment; filename=comparePrice.xls")
		List fields = ['area','ownStation','93#','97#','0#','type','stationName','93#1','97#1','0#1','promoting']
		Map labels = [ 'area':"片区",'ownStation':"本站加油站",'93#':"93#汽",'97#':"97#汽",'0#':"0#柴",'type':"性质",'stationName':"竞争加油站",'93#1':"93#汽",'97#1':"97#汽",'0#1':"0#柴",'promoting':"其他促销"]
		exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		[result:mapList,startDay:startDay,endDay:endDay]
	}
	
	def comparePriceReport(Date startDay, Date endDay){
		def competitorStations = CompetitorStation.createCriteria().list(){
			groupProperty("stationArea")
			order "station", "asc"
		}
		def mapList = new ArrayList<HashMap>()
		competitorStations.each{c->
			def map = new HashMap()
			map.put("area", c.stationArea.areaName)
			map.put("ownStation", c.station.shortName)
			map.put("stationName", c.name)
			map.put("station", c)
			map.put("type", c.company.name)
			def gasTypes = StationGas.createCriteria().list(){
				createAlias('gasType','gt')
				le("gt.id", 3l)
				eq("station", c)
			}
			def os = c.station
			def gs = StationGas.createCriteria().list(){
				createAlias('gasType','gt')
				le("gt.id", 3l)
				eq("station", os)
			}
			def p1,p2,p3,p11,p22,p33
			gasTypes.each{g->
				if(g.gasType==GasType.get(2)){
					p1 = gasPriceService.getStationGasPrice(c, g.gasType)
				}
				if(g.gasType==GasType.get(3)){
					p2 = gasPriceService.getStationGasPrice(c, g.gasType)
				}
				if(g.gasType==GasType.get(1)){
					p3 = gasPriceService.getStationGasPrice(c, g.gasType)
				}
			}
			gs.each{g->
				if(g.gasType==GasType.get(2)){
					p11 = gasPriceService.getStationGasPrice(os, g.gasType)
				}
				if(g.gasType==GasType.get(3)){
					p22 = gasPriceService.getStationGasPrice(os, g.gasType)
				}
				if(g.gasType==GasType.get(1)){
					p33 = gasPriceService.getStationGasPrice(os, g.gasType)
				}
			}
			def promoteList = new ArrayList()
			def now = new Date()
			def promotings = Promoting.createCriteria().list(){
				createAlias('stationGas','sg')
				eq("sg.station", c)
				le("startDate", now)
				or{
					ge("endDate", now)
					isNull("endDate")
				}
			}
			promotings.each{p->
				if(p.description!=0&&p.description!=null){
					promoteList.add(p.description)
				}
			}
			if(promoteList.size==0) promoteList=null
			map.put('93#1', p1)
			map.put('97#1', p2)
			map.put('0#1', p3)
			map.put('93#', p11)
			map.put('97#', p22)
			map.put('0#', p33)
			map.put('promoting', promoteList)
			mapList.add(map)
		}
		return mapList
	}
	
}
